package com.power.sifa.approve.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.huaban.analysis.jieba.JiebaSegmenter;
import com.huaban.analysis.jieba.SegToken;
import com.plf.common.domain.PageDataResponse;
import com.plf.core.common.dao.OffersetTransformers;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.approve.dao.Apl_typical_caseDao;
import com.power.sifa.approve.model.Apl_main;
import com.power.sifa.approve.model.Apl_typical_case;
import com.power.sifa.approve.model.pageInfo.Apl_typical_casePageInfo;
import com.power.sifa.approve.model.pojo.vo.TypicalCaseVO;
import com.power.sifa.approve.service.Apl_mainService;
import com.power.sifa.approve.service.Apl_typical_caseService;
import com.power.sifa.correction.model.Cre_warning;
import com.power.sifa.util.CnwordUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.query.internal.NativeQueryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 典型案件收藏表业务层实现
 */
@Slf4j
@Service
public class Apl_typical_caseServiceImpl extends BaseServiceImpl implements Apl_typical_caseService {

    @Autowired
    private Apl_typical_caseDao dao;

    @Autowired
    private Apl_mainService apl_mainService;

    @Resource
    private EntityManager entityManager;

    @Override
    public Apl_typical_case getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Apl_typical_case apl_typical_case) {
        // 查询当前数据的案号
        Apl_main apl_main = apl_mainService.getById(apl_typical_case.getApplyid());
        apl_typical_case.setAcceptcode(apl_main.getAcceptcode());
        // save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (apl_typical_case.getPrimaryKey() != null) {
            Apl_typical_case apl_typical_casefDb = dao.findById(apl_typical_case.getPrimaryKey()).orElse(null);
            if (apl_typical_casefDb != null) {
                BeanUtils.copyProperties(apl_typical_case, apl_typical_casefDb);
                dao.save(apl_typical_casefDb);
                return;
            }
        }
        dao.save(apl_typical_case);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Apl_typical_case> findAll(Apl_typical_casePageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if ("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        } else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber() <= 1 ? 0 : pageInfo.getPageNumber() - 1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
    public List<Apl_typical_case> findAll() {
        return dao.findAll();
    }

    @Override
    public void saveAll(List<Apl_typical_case> list) {
        dao.saveAll(list);
    }

    @Override
    public List<Apl_typical_case> conditionQuery(Apl_typical_casePageInfo pageInfo) {
        if (pageInfo != null && pageInfo.getQueryScope() != null) {
            if (pageInfo.getQueryScope().equals(0)) {
                return typicalQuery(pageInfo);
            } else {
                return mainReviewQuery(pageInfo);
            }
        }
        return Collections.emptyList();
    }

    @Override
    public Apl_typical_case getTypicalDataByUserId(String applyid, String userId) {
        Specification<Apl_typical_case> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.and(criteriaBuilder.equal(root.get("applyid"), applyid),
                        criteriaBuilder.equal(root.get("createuserid"), userId))
        ).getRestriction();
        List<Apl_typical_case> typicalCase = dao.findAll(specification);
        return CollectionUtil.isNotEmpty(typicalCase) ? typicalCase.get(0) : null;
    }

    @Override
    public PageDataResponse pageTypicalCase(Apl_typical_casePageInfo pageInfo) {
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber() - 1, pageInfo.getPageSize());
//        Page<TypicalCaseVO> typicalCaseList = this.dao.pageTypicalCase(pageable);
//        if (ObjectUtil.isNull(typicalCaseList)) {
//            return null;
//        }
//        for (TypicalCaseVO caseVO : typicalCaseList) {
//            log.warn("典型案例:{}", caseVO);
//        }
//        PageDataResponse pageResult = new PageDataResponse(typicalCaseList.getContent(), typicalCaseList.getTotalElements(),
//                typicalCaseList.getSize(), pageable.getPageNumber() <= 1 ? 1 : pageable.getPageNumber());
        return this.dao.pageTypicalCase(pageable);
    }


    /**
     * 典型案例查询
     *
     * @param pageInfo
     * @return
     */
    public List<Apl_typical_case> typicalQuery(Apl_typical_casePageInfo pageInfo) {
        List<Apl_typical_case> result = new ArrayList<>();
        StringBuffer sqlBuffer = new StringBuffer("select s.*, a.instid as instid from Apl_typical_case s left join " +
                "Apl_main a on s.applyid = a.id where 1=1 ");
        if (pageInfo.getQueryMode().equals(1)) {
            // 申请人匹配查询
            int index = 1;
            List<Object> paramsList = new ArrayList<>();
            if (StringUtils.isNotEmpty(pageInfo.getF_applyname())) {
                sqlBuffer.append(" and s.applyname = ?" + index++);
                paramsList.add(pageInfo.getF_applyname());
            }
            if (StringUtils.isNotEmpty(pageInfo.getF_classify())) {
                sqlBuffer.append(" and s.classify = ?" + index++);
                paramsList.add(pageInfo.getF_classify());
            }

            if (StringUtils.isNotEmpty(pageInfo.getF_applyid())) {
                sqlBuffer.append(" and s.applyid != ?" + index++);
                paramsList.add(pageInfo.getF_applyid());
            }

            Query query = entityManager.createNativeQuery(sqlBuffer.toString());
            query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);
            // 添加条件
            for (int i = 0; i <= paramsList.size() - 1; i++) {
                query.setParameter(i + 1, paramsList.get(i));
            }
            // 查询总数
            pageInfo.setAllcount(query.getResultList().size());
            // 分页
            if (pageInfo.getAllcount() > 0) {
                int pageStart = (pageInfo.getPageNumber() - 1) * pageInfo.getPageSize();
                List<Map> list = query.setFirstResult(pageStart).setMaxResults(pageInfo.getPageSize()).getResultList();
                if (CollectionUtil.isNotEmpty(list)) {
                    result = JSON.parseArray(JSON.toJSONString(list), Apl_typical_case.class);
                }
            }
            return result;
        } else if (pageInfo.getQueryMode().equals(2)) {
            // 被申请人匹配查询
            int index = 1;
            List<Object> paramsList = new ArrayList<>();
            if (StringUtils.isNotEmpty(pageInfo.getF_applyname())) {
                sqlBuffer.append(" and s.targetname = ?" + index++);
                paramsList.add(pageInfo.getF_targetname());
            }
            if (StringUtils.isNotEmpty(pageInfo.getF_classify())) {
                sqlBuffer.append(" and s.classify = ?" + index++);
                paramsList.add(pageInfo.getF_classify());
            }

            if (StringUtils.isNotEmpty(pageInfo.getF_applyid())) {
                sqlBuffer.append(" and s.applyid != ?" + index++);
                paramsList.add(pageInfo.getF_applyid());
            }
            Query query = entityManager.createNativeQuery(sqlBuffer.toString());
            query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);

            // 添加条件
            for (int i = 0; i <= paramsList.size() - 1; i++) {
                query.setParameter(i + 1, paramsList.get(i));
            }
            // 查询总数
            pageInfo.setAllcount(query.getResultList().size());
            // 分页
            if (pageInfo.getAllcount() > 0) {
                int pageStart = (pageInfo.getPageNumber() - 1) * pageInfo.getPageSize();
                List<Map> list = query.setFirstResult(pageStart).setMaxResults(pageInfo.getPageSize()).getResultList();
                if (CollectionUtil.isNotEmpty(list)) {
                    result = JSON.parseArray(JSON.toJSONString(list), Apl_typical_case.class);
                }
            }
            return result;
        } else {
            // 案由匹配查询
            int index = 1;
            List<Object> paramsList = new ArrayList<>();
            if (StringUtils.isNotEmpty(pageInfo.getF_classify())) {
                sqlBuffer.append(" and s.classify = ?" + index++);
                paramsList.add(pageInfo.getF_classify());
            }
            if (StringUtils.isNotEmpty(pageInfo.getF_applyid())) {
                sqlBuffer.append(" and s.applyid != ?" + index++);
                paramsList.add(pageInfo.getF_applyid());
            }
            // 将案由进行分词
            List<String> conWords = new ArrayList<>();
            if (StringUtils.isNotEmpty(pageInfo.getF_casecause())) {
                JiebaSegmenter segmenter = new JiebaSegmenter();
                List<SegToken> tokens = segmenter.process(pageInfo.getF_casecause(), JiebaSegmenter.SegMode.INDEX);
                conWords = tokens.stream()
                        .map(tk -> tk.word)
                        .filter(t -> t != null && !t.isEmpty())
                        .collect(Collectors.toCollection(LinkedList::new));
            }
            // 判断案由分词大小
            if (CollectionUtil.isNotEmpty(conWords)) {
                if (conWords.size() > 10) {
                    conWords = conWords.subList(0, 10);
                }
                // 拼接
                sqlBuffer.append(" and ( ");
                for (int conIndex = 0; conIndex < conWords.size(); conIndex++) {
                    if (conIndex > 0) {
                        sqlBuffer.append(" or ");
                    }
                    sqlBuffer.append(" s.casecause like " + "\'%" + conWords.get(conIndex) + "%\' ");
                }
                sqlBuffer.append(" ) ");
            }


            Query query = entityManager.createNativeQuery(sqlBuffer.toString());
            query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);
            // 添加条件
            for (int i = 0; i <= paramsList.size() - 1; i++) {
                query.setParameter(i + 1, paramsList.get(i));
            }

            // 查询总数
            pageInfo.setAllcount(query.getResultList().size());
            // 分页
            if (pageInfo.getAllcount() > 0) {
                int pageStart = (pageInfo.getPageNumber() - 1) * pageInfo.getPageSize();
                List<Map> list = query.setFirstResult(pageStart).setMaxResults(pageInfo.getPageSize()).getResultList();
                if (CollectionUtil.isNotEmpty(list)) {
                    result = JSON.parseArray(JSON.toJSONString(list), Apl_typical_case.class);
                }
            }
            // 基准案由
            String baseCasuse = pageInfo.getF_casecause();
            if (CollectionUtil.isNotEmpty(result)) {
                // 执行相似度算法 拿取对应相似度的数据
                List<Apl_typical_case> finalResult = new ArrayList<>();
                result.forEach(item -> {
                    if (StringUtils.isEmpty(baseCasuse) && StringUtils.isEmpty((item.getCasecause()))) {
                        // 同时为空 则显示100%
                        item.setSimilary(100.00);
                    } else {
                        BigDecimal similarity = BigDecimal.valueOf(CnwordUtil.findSimilarity(item.getCasecause(), baseCasuse) * 100);
                        double formate_similarity = similarity.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        item.setSimilary(formate_similarity);
                    }
                });
            }
            return result;
        }
    }


    /**
     * 典型案例查询
     *
     * @param pageInfo
     * @return
     */
    public List<Apl_typical_case> mainReviewQuery(Apl_typical_casePageInfo pageInfo) {
        List<Apl_typical_case> result = new ArrayList<>();
        StringBuffer sqlBuffer = new StringBuffer("select s.*, s.id as applyid, s.reason as casecause,a.acceptcode, a.instid as instid " +
                "from Apl_admreview s left join Apl_main a on s.id = a.id where 1=1 and acceptcode is not null ");
        if (pageInfo.getQueryMode().equals(1)) {
            // 申请人匹配查询
            int index = 1;
            List<Object> paramsList = new ArrayList<>();
            if (StringUtils.isNotEmpty(pageInfo.getF_applyname())) {
                sqlBuffer.append(" and s.applyname = ?" + index++);
                paramsList.add(pageInfo.getF_applyname());
            }
            if (StringUtils.isNotEmpty(pageInfo.getF_applyid())) {
                sqlBuffer.append(" and s.id != ?" + index++);
                paramsList.add(pageInfo.getF_applyid());
            }
            Query query = entityManager.createNativeQuery(sqlBuffer.toString());
            query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);
            // 添加条件
            for (int i = 0; i <= paramsList.size() - 1; i++) {
                query.setParameter(i + 1, paramsList.get(i));
            }
            // 查询总数
            pageInfo.setAllcount(query.getResultList().size());
            // 分页
            if (pageInfo.getAllcount() > 0) {
                int pageStart = (pageInfo.getPageNumber() - 1) * pageInfo.getPageSize();
                List<Map> list = query.setFirstResult(pageStart).setMaxResults(pageInfo.getPageSize()).getResultList();
                if (CollectionUtil.isNotEmpty(list)) {
                    result = JSON.parseArray(JSON.toJSONString(list), Apl_typical_case.class);
                }
            }
            return result;
        } else if (pageInfo.getQueryMode().equals(2)) {
            // 被申请人匹配查询
            int index = 1;
            List<Object> paramsList = new ArrayList<>();
            if (StringUtils.isNotEmpty(pageInfo.getF_applyname())) {
                sqlBuffer.append(" and s.targetname = ?" + index++);
                paramsList.add(pageInfo.getF_targetname());
            }
            if (StringUtils.isNotEmpty(pageInfo.getF_applyid())) {
                sqlBuffer.append(" and s.id != ?" + index++);
                paramsList.add(pageInfo.getF_applyid());
            }
            Query query = entityManager.createNativeQuery(sqlBuffer.toString());
            query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);

            // 添加条件
            for (int i = 0; i <= paramsList.size() - 1; i++) {
                query.setParameter(i + 1, paramsList.get(i));
            }
            // 查询总数
            pageInfo.setAllcount(query.getResultList().size());
            // 分页
            if (pageInfo.getAllcount() > 0) {
                int pageStart = (pageInfo.getPageNumber() - 1) * pageInfo.getPageSize();
                List<Map> list = query.setFirstResult(pageStart).setMaxResults(pageInfo.getPageSize()).getResultList();
                if (CollectionUtil.isNotEmpty(list)) {
                    result = JSON.parseArray(JSON.toJSONString(list), Apl_typical_case.class);
                }
            }
            return result;
        } else {
            // 案由匹配查询

            int index = 1;
            List<Object> paramsList = new ArrayList<>();
            if (StringUtils.isNotEmpty(pageInfo.getF_applyid())) {
                sqlBuffer.append(" and s.id != ?" + index++);
                paramsList.add(pageInfo.getF_applyid());
            }
            // 将案由进行分词
            List<String> conWords = new ArrayList<>();
            if (StringUtils.isNotEmpty(pageInfo.getF_casecause())) {
                JiebaSegmenter segmenter = new JiebaSegmenter();
                List<SegToken> tokens = segmenter.process(pageInfo.getF_casecause(), JiebaSegmenter.SegMode.INDEX);
                conWords = tokens.stream()
                        .map(tk -> tk.word)
                        .filter(t -> t != null && !t.isEmpty())
                        .collect(Collectors.toCollection(LinkedList::new));
            }
            // 判断案由分词大小
            if (CollectionUtil.isNotEmpty(conWords)) {
                if (conWords.size() > 10) {
                    conWords = conWords.subList(0, 10);
                }
                // 拼接
                sqlBuffer.append(" and ( ");
                for (int conIndex = 0; conIndex < conWords.size(); conIndex++) {
                    if (conIndex > 0) {
                        sqlBuffer.append(" or ");
                    }
                    sqlBuffer.append(" s.reason like " + "\'%" + conWords.get(conIndex) + "%\' ");
                }
                sqlBuffer.append(" ) ");
            }


            Query query = entityManager.createNativeQuery(sqlBuffer.toString());
            query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);
            // 添加条件
            for (int i = 0; i <= paramsList.size() - 1; i++) {
                query.setParameter(i + 1, paramsList.get(i));
            }

            // 查询总数
            pageInfo.setAllcount(query.getResultList().size());
            // 分页
            if (pageInfo.getAllcount() > 0) {
                int pageStart = (pageInfo.getPageNumber() - 1) * pageInfo.getPageSize();
                List<Map> list = query.setFirstResult(pageStart).setMaxResults(pageInfo.getPageSize()).getResultList();
                if (CollectionUtil.isNotEmpty(list)) {
                    result = JSON.parseArray(JSON.toJSONString(list), Apl_typical_case.class);
                }
            }
            // 基准案由
            String baseCasuse = pageInfo.getF_casecause();
            if (CollectionUtil.isNotEmpty(result)) {
                // 执行相似度算法 拿取对应相似度的数据
                List<Apl_typical_case> finalResult = new ArrayList<>();
                result.forEach(item -> {
                    if (StringUtils.isEmpty(baseCasuse) && StringUtils.isEmpty((item.getCasecause()))) {
                        // 同时为空 则显示100%
                        item.setSimilary(100.00);
                    } else {
                        BigDecimal similarity = BigDecimal.valueOf(CnwordUtil.findSimilarity(item.getCasecause(), baseCasuse) * 100);
                        double formate_similarity = similarity.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        item.setSimilary(formate_similarity);
                    }
                });
            }
            return result;
        }


    }
}
